<template>
	<view class="editUser">
		<view class="con avatar">
			<view class="label">
				头像
			</view>
			<view class="value">
				<image class="avatarImg" :src="user.avatarUrl" mode="aspectFill"></image>
			</view>
			<button style="background-color: white; padding: 0rpx;margin: 0;" open-type="chooseAvatar"
				@chooseavatar="changeAvatar">
				<van-icon name="arrow" />
			</button>
		</view>
		<view class="con nickName">
			<view class="label">
				昵称
			</view>
			<view class="value">
				{{user.username}}
			</view>
			<button style="background-color: white; padding: 0rpx;margin: 0;" @click="editUsername">
				<van-icon name="arrow" />
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue'
	import {
		updateUserInf,
		getUserInf
	} from '@/apis/apis.js'
	import {
		useUserStore
	} from '@/store';
	const useUser = useUserStore();
	const user = ref()
	// onMounted(() => {
	user.value = useUser.userInf
	// console.log(user.value, '?');
	// })
	const nickName = ref('')
	const changeAvatar = async (e) => {
		const apiUrl = 'https://tww.jyu.edu.cn';
		// const apiUrl = 'https://jyutw.alcy.top'
		try {
			const avatarPath = e.detail.avatarUrl; // 获取选中的头像临时路径
			if (!avatarPath) {
				uni.showToast({
					title: '请选择头像',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				title: '上传中...'
			});

			// 上传文件
			const res = await uni.uploadFile({
				url: `${apiUrl}/apis/uploadFiles`, // 替换为你的后端文件上传接口
				filePath: avatarPath,
				name: 'file', // 后端接收的字段名
				header: {
					'Authorization': 'Bearer ' + uni.getStorageSync('jyu_token') ||
						useUser
							.token || ''
				},
			});
			console.log(res.data);
			const response = JSON.parse(res.data); // uni.uploadFile 的返回内容在 data 中是 JSON 字符串
			if (response.status === 200) {
				const avatarUrl = response.filePaths[0]; // 获取上传后的头像 URL

				// 更新用户信息
				const updateRes = await editInfo({
					avatarUrl: apiUrl + avatarUrl
				});
				if (updateRes.status === 200) {
					const newAvatarUrl = apiUrl + avatarUrl;
					useUser.userInf.avatarUrl = newAvatarUrl; // 更新全局状态
					user.value.avatarUrl = newAvatarUrl; // 更新当前组件的用户信息
					console.log(newAvatarUrl);
					uni.showToast({
						title: '头像修改成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '头像修改失败',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: '上传失败，请重试',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('修改头像失败:', error);
			uni.showToast({
				title: '修改头像失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};

	const editUsername = () => {
		uni.showModal({
			title: '修改名字',
			editable: true,
			content: user.value.username,
			success: function(res) {
				if (res.confirm) {
					if (res.content == user.value.username) {
						console.log('nxnmn？')
					} else {
						editInfo({
							username: res.content
						}).then(resTe => {
							if (resTe.status === 200) {
								useUser.userInf.username = res.content
								user.value.username = res.content
								setTimeout(() => {
									uni.showToast({
										title: resTe.message,
									})
								}, 1000)
							}
						})
					}
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	const editInfo = async (data) => {
		const resTemp = await updateUserInf(data)
		console.log(resTemp)
		return resTemp
	}
</script>

<style lang="less">
	.editUser {
		width: 100%;
		padding-top: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 30rpx;

		.con {
			height: 160rpx;
			width: 95%;
			background-color: white;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			box-sizing: border-box;
			padding: 30rpx;

			.label {
				font-size: 35rpx;
			}

			.value {
				margin-left: auto;
				margin-right: 40rpx;
				overflow: hidden;

				.avatarImg {
					height: 120rpx;
					width: 120rpx;
				}
			}
		}
	}
</style>